
package com.scalar.chiptrack.sales.actions;

import java.util.*;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;

import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.CustomerRelationshipDAO;
import com.scalar.chiptrack.sales.CustomerPartNumber;


public class CustomerPartNumbersAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/customerPartNumbers.do" ;

    public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                     throws Exception {

        HttpSession session = request.getSession();
        HashMap errors = new HashMap();
		request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);


		HashMap info = new HashMap();
		request.setAttribute (SessionKeys.INFO_MESSAGES, info);
        User user = (User)session.getAttribute (SessionKeys.USER_KEY);

        if (user == null)
        {
            session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
            return (mapping.findForward ("login"));
        }
        String customerId = request.getParameter("customerId");
        int custId =0;
		String action = request.getParameter("action");

      	if("SaveCustomerPartNumbers".equalsIgnoreCase(action))
        {
            if ( getAllCustomerPartNumbers(customerId,request) )
            {
                custId = Integer.parseInt(customerId);
                info.put("Customer Part Numbers saved successfully",null); /*modified by Krishna Prasad on 20 May 2004 , just the changed the message*/
                request.setAttribute("mfgPartsWithProductIds", SalesOrderDAO.loadAllMfgPartNumbersWithProductIds(custId));
            }
            else
            {
                request.setAttribute("mfgPartsWithProductIds", loadAllMfgPartNumbersWithProductIds( request ));
            }
            return (mapping.findForward ("success"));
        }
        if(customerId != null)
        {
            custId = Integer.parseInt(customerId);
            request.setAttribute("mfgPartsWithProductIds", SalesOrderDAO.loadAllMfgPartNumbersWithProductIds(custId));
            //session.setAttribute("OdmAndEndCustomers", CustomerRelationshipDAO.getAllOdmsAndEndCustomers( custId+"" ) );
            session.setAttribute("odmNamesList", CustomerRelationshipDAO.getAllOdmsForCustomer( custId+"" ));
        }

        //Added by varma 10 Jan 2005
        if("printView".equalsIgnoreCase(action))
        {
             try{
                 custId = Integer.parseInt(customerId);
            }catch( NumberFormatException ignore){}

            //To load the Client Address Id
            String clientaddressId =  UserDAO.getClientAddressId();
            String addressId = null;
            String clientname = null;

            int finalAddressId = 0;
            if(clientaddressId != null)
            {
                StringTokenizer st = new StringTokenizer(clientaddressId,"@");
                try
                {
                    addressId = st.nextToken();
                    clientname = st.nextToken();
                }catch( NoSuchElementException e )
                {
                     clientname  = "";
                }
            }
            if(addressId  != null)
            {
                finalAddressId = Integer.parseInt(addressId);
            }
            //Load the Client Address Details
            Address clientAddress= UserDAO.loadClientAddressDetails( null , finalAddressId );

            request.setAttribute("customerName", CustomerDAO.getCustomerName(null, custId ) );
            request.setAttribute( "clientName", clientname );
            request.setAttribute( "clientAddressAsAirgoFormatted", getClientAddrWithOutEmailObjFormattedAirgo(clientAddress,clientname ) );
            request.setAttribute( "mfgPartsWithProductIdsWithOdmNames", loadAllMfgPartNumbersWithProductIdsAndOdmNames( SalesOrderDAO.loadAllMfgPartNumbersWithProductIds( custId ) ) );
            return ( mapping.findForward ("printView") );
        }

        return (mapping.findForward ("success"));
    }

    private static boolean getAllCustomerPartNumbers(String customerId,HttpServletRequest request) throws ScalarException
    {
        int custid = 0;

        String[] productIds = request.getParameterValues("productId");
        String[] customerPartNumbers = request.getParameterValues("customerPartNo");
        String[] labelNumbers = request.getParameterValues("labelNumber");
        String[] odmIds = request.getParameterValues("odmId");
        HashMap errors = new HashMap ();

        if(customerId != null)
        {
            custid = Integer.parseInt(customerId);
        }
        String odmName = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endCustomer" );


        for ( int i = 0 ; i < productIds.length - 1; i++ )
        {
            for ( int j = i+1 ; j < productIds.length; j++ )
            {
                if( ( productIds[i] != null && productIds[i].length() != 0) && ( (customerPartNumbers[i] != null &&  customerPartNumbers[i].length() != 0 ) ) &&
                    ( productIds[j] != null && productIds[j].length() != 0) && ( (customerPartNumbers[j] != null &&  customerPartNumbers[j].length() != 0 ) ) &&
                    ( productIds[i].equalsIgnoreCase( productIds[j] ) ) && ( odmIds[i].equalsIgnoreCase( odmIds[j] ) ) && ( customerPartNumbers[i].equalsIgnoreCase( customerPartNumbers[j] ) ) )
                {
                    errors.put( "Combination of Part Number, Customer Part Number and "+odmName+" should not be repeated", null);
                    break;
                }
                //if we allow the end customer part numbers means no need check for diplication .
                /*if( !ConfigManager.isEndUserPartNumbersAllowed() ){
                if( ( productIds[i] != null && productIds[i].length() != 0) && ( (customerPartNumbers[i] != null &&  customerPartNumbers[i].length() != 0 ) || (labelNumbers[i] != null && labelNumbers[i].length() != 0 ) )
                     && ( productIds[j] != null && productIds[j].length() != 0) && ( (customerPartNumbers[j] != null &&  customerPartNumbers[j].length() != 0 ) || (labelNumbers[j] !=null && labelNumbers[j].length() != 0))
                     && ( productIds[i].equalsIgnoreCase( productIds[j] ) ) && ( odmIds[i].equalsIgnoreCase( odmIds[j] ) ) )
                {
                    errors.put( "Combination of Part Number and "+odmName+" / Customer should not be repeated", null);
                    break;
                }                
                }*/
            }
        }
        if ( errors.isEmpty () )
        {
            try
            {
                CustomerDAO.saveCustomerPartNumbers( custid, productIds, customerPartNumbers, labelNumbers, odmIds );
            }
            catch( Exception e)
            {
                errors.put( "Could not save Part Numbers", null );
            }
        }
        if ( !errors.isEmpty () )
        {
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
            return false;
        }
        return true;
    }
    private static ArrayList loadAllMfgPartNumbersWithProductIds( HttpServletRequest request )
    {
        String[] productIds = request.getParameterValues("productId");
        String[] manufacturingPartNo = request.getParameterValues("hiddenMfgPartNo");
        String[] customerPartNumbers = request.getParameterValues("customerPartNo");
        String[] labelNumbers = request.getParameterValues("labelNumber");
        String[] odmIds = request.getParameterValues("odmId");

        ArrayList partNumbersList = new ArrayList();
        CustomerPartNumber customerPartNo = null;
        for ( int i = 0; i < customerPartNumbers.length ; i++ )
        {
            customerPartNo = new CustomerPartNumber();
            customerPartNo.setProductId( Integer.parseInt( productIds[ i ] ) );
            customerPartNo.setManufacturingPartNo( manufacturingPartNo[i] );
            customerPartNo.setCustomerPartNo( customerPartNumbers[i] );
            customerPartNo.setLabelNumber( labelNumbers[i] );
            customerPartNo.setOdmId( Integer.parseInt(odmIds[i] ));
            partNumbersList.add(customerPartNo);
        }
        return partNumbersList;
    }


    public static String getClientAddrWithOutEmailObjFormattedAirgo(Address address,String clientname )
	{

		StringBuffer formatAddress = new StringBuffer();

        if( address != null )
        {
            if( clientname != null && clientname.trim().length() > 0 ) {
                if( ( address.getAddress1() != null && !address.getAddress1().trim().equalsIgnoreCase( "" ) )
                      || ( address.getAddress2() != null && !address.getAddress2().trim().equalsIgnoreCase( "" ) ) ) {
                    formatAddress.append ( "<BR>" );
                }
            }
            if( address.getAddress1() != null && ( address.getAddress1().trim().length() != 0 ) ){
                formatAddress.append ( address.getAddress1() );
            }
            if( address.getAddress1() != null && ( address.getAddress1().trim().length() != 0 )
                && address.getAddress2() != null && ( address.getAddress2().trim().length() != 0 ) ){
                formatAddress.append ( ", " );
            }
            if( address.getAddress2() != null && ( address.getAddress2().trim().length() != 0 ) ){
                formatAddress.append ( address.getAddress2() );
            }
            if( ( address.getAddress3() != null && !"".equalsIgnoreCase(address.getAddress3().trim()) )
                  || ( address.getAddress4() != null && !"".equalsIgnoreCase(address.getAddress4().trim()) ) ) {
                formatAddress.append ( "<BR>" );
            }
            if( address.getAddress3() != null && ( address.getAddress3().trim().length() != 0 ) ){
                formatAddress.append ( address.getAddress3 () );
            }
            if( address.getAddress3() != null && !"".equals(address.getAddress3().trim())
                && address.getAddress4() != null && !"".equals(address.getAddress4().trim())) {
                formatAddress.append ( ", " );
            }
            if( address.getAddress4() != null && ( address.getAddress4().trim().length() != 0 ) ){
                formatAddress.append ( address.getAddress4 () );
            }

            StringBuffer cityStateZip = new StringBuffer ( "" );

            if ( address.getCity() != null && !"".equals( address.getCity() ) ) {
                cityStateZip.append ( address.getCity () );
            }

            // address ',' only if city, state, zip are not empty
            if ( address.getCity() != null && !"".equals( address.getCity() )
                 && ( (  address.getState() != null && !"".equals(address.getState()))
                 || ( address.getZipCode()!= null  && !"".equals(address.getZipCode())) ) ) {
                cityStateZip.append ( ", " );
            }

            if ( address.getState() != null && !"".equals( address.getState() ) ) {
                cityStateZip.append( address.getState () );
            }

            // Add '-' only if there is state and Zip also
            if ( address.getState() != null && !"".equals( address.getState() )
                 && address.getZipCode () != null && !"".equals( address.getZipCode () ) ) {
                cityStateZip.append ( " - " );
            }

            if ( address.getZipCode()!= null && !"".equals( address.getZipCode() ) ) {
                cityStateZip.append ( address.getZipCode () );
            }

            // address ',' if any of the above is present
            if ( (  ( address.getCity() != null && !"".equals(address.getCity())  )
                    || ( address.getState() != null && !"".equals(address.getState()) )
                    || ( address.getZipCode() != null &&  !"".equals(address.getZipCode()) ) )
                    && address.getCountry() != null && !"".equalsIgnoreCase( address.getCountry() ) )

            {
                cityStateZip.append ( ", " );
                cityStateZip.append ( address.getCountry () );
            }
            if( cityStateZip != null && cityStateZip.toString().trim().length() > 0  )
            {
                formatAddress.append ( "<BR>" + cityStateZip );
            }

            StringBuffer phFax = new StringBuffer ();

            if( address.getPhoneNumber() != null && !"".equals( address.getPhoneNumber() ) ) {
                phFax.append ( "T: " + address.getPhoneNumber () );
            }

            if( address.getPhoneNumber() != null && !"".equals( address.getPhoneNumber() )
                &&  address.getFaxNumber() != null && !"".equals ( address.getFaxNumber() ) ) {
                phFax.append ( ",&nbsp;" );
            }

            if( address.getFaxNumber() != null && !"".equals( address.getFaxNumber() ) ) {
                phFax.append ( "F: " + address.getFaxNumber () );
            }

            if( phFax != null && phFax.toString().trim().length() > 0  ) {
                formatAddress.append ( "<BR>" + phFax );
            }

            if( Constants.AIRGO_WEBSITE != null && Constants.AIRGO_WEBSITE .trim() .length() > 0 ) {
                formatAddress.append ( "<BR>" + Constants.AIRGO_WEBSITE );
            }

       }
        return formatAddress.toString() ;
	}
   //Added by Varma 11 Jan 2005 to load the ODM Name to part Numbers list based on ODM Id.
    public static ArrayList loadAllMfgPartNumbersWithProductIdsAndOdmNames( ArrayList partNumbersList) throws ScalarException
    {
        ArrayList finalList = new ArrayList();
        for(int i= 0; i<partNumbersList.size() ;i++)
        {
            CustomerPartNumber customerPartNumber = ( CustomerPartNumber )partNumbersList.get( i );
            int odmId = customerPartNumber.getOdmId();
            if( odmId > 0 ){
                String odmName =  CustomerDAO.getCustomerName( null,customerPartNumber.getOdmId() );
                customerPartNumber.setOdmName( odmName );
            }
            finalList.add( customerPartNumber );
        }

        return finalList;
    }


    public static String getPartNumbersAckPDFFile ( String host, String customerId ) throws ScalarException
    {
        String fileXMLPath = null;
        String filePDFPath = null;
        String customerName = null;
        int custId = -1;
        try{
            custId = Integer.parseInt(customerId) ;
        }catch(NumberFormatException ignore){}

        ArrayList partNumbersList = loadAllMfgPartNumbersWithProductIdsAndOdmNames(SalesOrderDAO.loadAllMfgPartNumbersWithProductIds( custId ) );
        customerName = CustomerDAO.getCustomerName( null, custId );
        String saAsXML = formatAsXML ( partNumbersList , customerName );

        if ( saAsXML == null )
        {
            return fileXMLPath;
        }

        FileWriter fWriter = null;
        File saPDFAttachment = null;
        File saXML = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();

            String xmlFileName = "PartNumber_Ack_" + customerName + ".xml";
            String saAttachmentPDFFileName = "PartNumber_Ack_" + customerName + ".pdf";

            String xsltFileName = ConfigManager.getPartNumbersAckXml2PdfXslFile ();

            saXML = new File ( tempDir.getCanonicalPath (), xmlFileName );
            saXML.deleteOnExit ();

            saPDFAttachment = new File ( tempDir.getCanonicalPath (), saAttachmentPDFFileName );
            saPDFAttachment.deleteOnExit ();

            if ( ( saXML.exists () == true ) || ( saXML.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( saXML, false );
                fWriter.write ( saAsXML );
                fWriter.close ();
                fWriter = null;

                fileXMLPath = saXML.getCanonicalPath ().toLowerCase ();
                filePDFPath = saPDFAttachment.getCanonicalPath ().toLowerCase ();

                boolean success = PDFGenerator.convertXML2PDF ( fileXMLPath, xsltFileName, filePDFPath );

            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Sales Order Ack PDF file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePDFPath;
    }

    public static String formatAsXML ( ArrayList partNumbersList, String customerName ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        Calendar calendar = new GregorianCalendar();


        //To load the Client Address Id
        String clientaddressId =  UserDAO.getClientAddressId();
        String addressId = null;
        String clientname = null;

        int finalAddressId = 0;
        if(clientaddressId != null)
        {
            StringTokenizer st = new StringTokenizer(clientaddressId,"@");
            try
            {
                addressId = st.nextToken();
                clientname = st.nextToken();
            }catch( NoSuchElementException e )
            {
                 clientname  = "";
            }
        }
        if(addressId  != null)
        {
            finalAddressId = Integer.parseInt(addressId);
        }
        //Load the Client Address Details
        Address clientAddress= UserDAO.loadClientAddressDetails( null , finalAddressId );
        buf.append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" );
        buf.append ( "<partNumbersAcknowledgement>" + "\n" );
        buf.append ( "<logo>" + ConfigManager.getChipTracImagesDir () + ConfigManager.getScalarLogo () + "</logo>" + "\n" );

        buf.append ( "<selfAddress>" + "\n" );
        buf.append ( "<name><![CDATA[" + clientname + "]]></name>" + "\n" );

        String addressStr = getXMLFormattedAddressAirgo( clientAddress );

        buf.append ( addressStr );
        buf.append ( "<webSite><![CDATA[" + Constants.AIRGO_WEBSITE + "]]></webSite>" + "\n" );
        buf.append ( "</selfAddress>" + "\n" );

        String date = ( ( calendar.get( Calendar.MONTH ) ) + 1 ) + "/" + calendar.get( Calendar.DATE )  + "/" + calendar.get( Calendar.YEAR );
        buf.append ( "<date><![CDATA[" + StringUtils.formatDate( date ) + "]]></date>" + "\n" );
        //To get the labels from application resources
        String custPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( custPartNumberLabel == null )
        {
            custPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }
        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }
        String labelNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.labelNumber" );
        if ( labelNumberLabel == null )
        {
            labelNumberLabel = Labels.DEFAULT_LABEL_NUMBER_LABEL;
        }

        CustomerPartNumber customerPartNumber = null;
        buf.append ( "<customerName><![CDATA[" + customerName + "]]></customerName>" + "\n" );
        buf.append ( "<custPartNumberLabel><![CDATA[" + custPartNumberLabel + "]]></custPartNumberLabel>" + "\n" );
        buf.append ( "<partNumbers>" + "\n" );
        buf.append ( "<mfgPartNumberLabel><![CDATA[" + mfgPartNumberLabel + "]]></mfgPartNumberLabel>" + "\n" );
        buf.append ( "<custPartNumberLabel><![CDATA[" + custPartNumberLabel + "]]></custPartNumberLabel>" + "\n" );
        buf.append ( "<labelNumberLabel><![CDATA[" + labelNumberLabel + "]]></labelNumberLabel>" + "\n" );
        int bgcount = 0;
        for ( int j = 0; j < partNumbersList.size() ; j++ )
        {
            customerPartNumber = ( CustomerPartNumber ) partNumbersList.get ( j );
            boolean bgCount = false;

            if( customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- CHIPS -----") || customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- BOARD -----") || customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- KIT -----") ){
                bgcount = bgcount + 1;
                String mfgPart = "";

                if(customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- CHIPS -----")) { mfgPart = "CHIPS";}
                else if (customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- BOARD -----")){ mfgPart = "BOARD";}
                else { mfgPart = "KIT";}

                if( bgcount%2 == 0 ) bgCount = true;
                else  bgCount = false;

                buf.append ( "<partNumber>" + "\n" );
                buf.append ( "<bgCount><![CDATA["+ bgCount + "]]></bgCount>" + "\n" );
                buf.append ( "<title><![CDATA["+ true + "]]></title>" + "\n" );
                buf.append ( "<mfgPartNumber><![CDATA["+mfgPart + "]]></mfgPartNumber>" + "\n" );
                buf.append ( "</partNumber>" + "\n" );
            }
            else if( (customerPartNumber.getCustomerPartNo()!= null && customerPartNumber.getCustomerPartNo().trim().length() > 0) || (customerPartNumber.getLabelNumber()!= null && customerPartNumber.getLabelNumber().trim().length() > 0) )
            {   bgcount++;

                if( bgcount%2 == 0 ) bgCount = true;
                else  bgCount = false;

                buf.append ( "<partNumber>" + "\n" );
                buf.append ( "<bgCount><![CDATA["+ bgCount + "]]></bgCount>" + "\n" );
                buf.append ( "<title><![CDATA["+ false + "]]></title>" + "\n" );
                buf.append ( "<mfgPartNumber><![CDATA["+customerPartNumber.getManufacturingPartNo() + "]]></mfgPartNumber>" + "\n" );
                buf.append ( "<custPartNumber><![CDATA["+customerPartNumber.getCustomerPartNo() + "]]></custPartNumber>" + "\n" );
                buf.append ( "<labelNumber><![CDATA["+customerPartNumber.getLabelNumber() + "]]></labelNumber>" + "\n" );
                buf.append ( "<odmName><![CDATA["+  ( ( ( customerPartNumber.getOdmName() != null ) && ( customerPartNumber.getOdmName().trim().length() > 0 ) ) ? customerPartNumber.getOdmName() : "" ) + "]]></odmName>" + "\n" );
                buf.append ( "</partNumber>" + "\n" );
            }

        }
        buf.append ( "</partNumbers>" + "\n" );
        buf.append ( "</partNumbersAcknowledgement>" + "\n" );

        return buf.toString() ;
    }

    public static String getPartNumbersAckHTMLFile ( String host, String customerId ) throws ScalarException
    {
        String filePath = null;

        String customerName = null;
        int custId = -1;
        try{
            custId = Integer.parseInt(customerId) ;
        }catch(NumberFormatException ignore){}

        ArrayList partNumbersList = loadAllMfgPartNumbersWithProductIdsAndOdmNames( SalesOrderDAO.loadAllMfgPartNumbersWithProductIds( custId ) );
        customerName = CustomerDAO.getCustomerName( null, custId );
        String saAsHTML = formatAsHTML ( host, partNumbersList, customerName );

        if ( saAsHTML == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            File tempDir = new File ( "chiptrac_temp_dir" ).getCanonicalFile ();
            tempDir.mkdir ();

            String salesAttachmentFileName = null;

            salesAttachmentFileName = "Part_Numbers_ACK#  " + customerName + ".html";
            psAttachment = new File ( tempDir.getCanonicalPath (), salesAttachmentFileName );
            psAttachment.deleteOnExit ();

            if ( ( psAttachment.exists () == true ) || ( psAttachment.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( psAttachment, false );

                fWriter.write ( saAsHTML );

                fWriter.close ();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Part Numbers Ack PDF file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePath;
    }

    public static String formatAsHTML ( String host, ArrayList partNumbersList, String customerName ) throws ScalarException
    {

        StringBuffer buf = new StringBuffer ( 2098 );
        Calendar calendar = new GregorianCalendar();

        //To load the Client Address Id
        String clientaddressId =  UserDAO.getClientAddressId();
        String addressId = null;
        String clientname = null;

        int finalAddressId = 0;
        if(clientaddressId != null)
        {
            StringTokenizer st = new StringTokenizer(clientaddressId,"@");
            try
            {
                addressId = st.nextToken();
                clientname = st.nextToken();
            }catch( NoSuchElementException e )
            {
                 clientname  = "";
            }
        }
        if(addressId  != null)
        {
            finalAddressId = Integer.parseInt(addressId);
        }
        //Load the Client Address Details
        Address clientAddress= UserDAO.loadClientAddressDetails( null , finalAddressId );
        buf.append ( "<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>" );
        buf.append ( "<LINK href='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet>" );
        buf.append ( "<style type='text/css'>" );
        buf.append ( "a { text-decoration : none}" );
        buf.append ( "</style>" );
        buf.append ( "</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>" );
        buf.append ( "<!-- from here your body starts -->" );

        buf.append ( "<Div1>");
        buf.append ( "<table width='90%' cellspacing='0' cellpadding='0' border=0 align=center>" );
        buf.append ( "<tr><td><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height='20'></td></tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td width='10%' valign='Top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/scalar_logo.jpg' height='70' width='160' border=0>&nbsp;&nbsp;</td>" );

        buf.append ( "<td width='25%' valign='Top'><font size='3'><b>" + clientname + "</b></font><font class='NArialS'> " + getClientAddrWithOutEmailObjFormattedAirgo(clientAddress,clientname )  + "</font>" );

        String custPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( custPartNumberLabel == null )
        {
            custPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }
        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }
        String labelNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.labelNumber" );
        if ( labelNumberLabel == null )
        {
            labelNumberLabel = Labels.DEFAULT_LABEL_NUMBER_LABEL;
        }
        buf.append ( "<td width='20%' valign='Top' nowrap><h4>"+custPartNumberLabel+"s</h4></td>" );

        String date = ( ( calendar.get( Calendar.MONTH ) ) + 1 ) + "/" + calendar.get( Calendar.DATE )  + "/" + calendar.get( Calendar.YEAR );
        buf.append ( "<td width='35%' align='center' class='NArialL' valign='TOP' ><h4>Date: "+ StringUtils.formatDate( date ) +"</h4></td>" );
        buf.append ( "</tr>" );

        buf.append ( "<tr><td><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height='40'></td></tr>" );
        buf.append ( "</table>" );

        buf.append ( "<table border='0' width='90%' bordercolor='#000000' align='center' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><td colspan='4' class='NArialL' colspan='4' align='center'><h5>Customer Name:&nbsp;" + customerName + "</h5></td></tr></table>");
        CustomerPartNumber customerPartNumber = null;

        buf.append ( "<table border='1' width='90%' bordercolor='#000000' align='center' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><td colspan='4'>");
        buf.append ( "<table border='0' width='100%'>");
        buf.append ( "<tr>");
        buf.append ( "<td width='25%' class='NArialL' bgcolor='#DEE1E2'>&nbsp;"+mfgPartNumberLabel+"</td>" );
        buf.append ( "<td width='25%' class='NArialL' bgcolor='#DEE1E2'>"+custPartNumberLabel+"</td>" );
        buf.append ( "<td width='25%' class='NArialL' bgcolor='#DEE1E2'>ODM Name</td>" );
        buf.append ( "<td width='25%' class='NArialL' bgcolor='#DEE1E2'>"+labelNumberLabel+"</td>" );
        buf.append ( "</tr></table></td> </tr>");
        buf.append ( "<tr><td colspan='4'> <table border='0' width='100%' cellspacing='0' cellpadding='2'>" );
        int bgcount = 0;

        for ( int j = 0; j < partNumbersList.size() ; j++ )
        {
            customerPartNumber = ( CustomerPartNumber ) partNumbersList.get ( j );

             if( customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- CHIPS -----") || customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- BOARD -----") || customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- KIT -----") ){
                bgcount = bgcount + 1;
                String mfgPart = "";
                if(customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- CHIPS -----")) { mfgPart = "CHIPS";}
                else if (customerPartNumber.getManufacturingPartNo().equalsIgnoreCase("---- BOARD -----")){ mfgPart = "BOARD";}
                else { mfgPart = "KIT";}

                buf.append ( "<tr><td align='center' colspan='4'");
                buf.append ( bgcount%2==0 ? "bgcolor='#DEE1E2'" : " bgcolor='#FFFFEE'>");
                buf.append ( "<font class='NArialL'><U>"+mfgPart +"</U></font></td> </tr>");
            }
            else if( (customerPartNumber.getCustomerPartNo()!= null && customerPartNumber.getCustomerPartNo().trim().length() > 0) || (customerPartNumber.getLabelNumber()!= null && customerPartNumber.getLabelNumber().trim().length() > 0) ){
                bgcount = bgcount + 1;
                buf.append ( "<tr><td width='25%' align='left'");
                buf.append ( bgcount%2==0 ? "bgcolor='#DEE1E2'" : " bgcolor='#FFFFEE'>");
                buf.append ( "<font class='NArialL'>&nbsp;"+customerPartNumber.getManufacturingPartNo() +"</font></td>");
                buf.append ( "<td width='25%' align='left'");
                buf.append ( bgcount%2==0 ? "bgcolor='#DEE1E2'" : " bgcolor='#FFFFEE'>");
                buf.append ( "<font class='NArialL'>"+customerPartNumber.getCustomerPartNo() +"</font></td> ");
                buf.append ( "<td width='25%' align='left'");
                buf.append ( bgcount%2==0 ? "bgcolor='#DEE1E2'" : " bgcolor='#FFFFEE'>");
                buf.append ( "<font class='NArialL'>"+( ( ( customerPartNumber.getOdmName() != null ) && ( customerPartNumber.getOdmName().trim().length() > 0 ) ) ? customerPartNumber.getOdmName() : "" ) +"</font></td> ");
                buf.append ( "<td width='25%' align='left'");
                buf.append ( bgcount%2==0 ? "bgcolor='#DEE1E2'" : " bgcolor='#FFFFEE'>");
                buf.append ( "<font class='NArialL'>"+customerPartNumber.getLabelNumber() +"</font></td> </tr>");
          }

        }
        buf.append ( "</table></td></tr></table>");

        buf.append ( "</body></html>" );

        return buf.toString() ;
    }

    public static String getXMLFormattedAddressAirgo( Address add )
    {
        StringBuffer formatAddress = new StringBuffer();

        formatAddress.append( "<address1><![CDATA[" );
        formatAddress.append ( ( ( add.getAddress1() == null ) || ( ( add.getAddress1().trim().length() == 0 ) ) ) ? "" : add.getAddress1() );

        if( add.getAddress1() != null && !( add.getAddress1().trim().length() == 0 ) && add.getAddress2() != null && !( add.getAddress2().trim().length() == 0 ) )
        formatAddress.append ( ", " );
        formatAddress.append ( add.getAddress2() );
        formatAddress.append ( "]]></address1> \n" );

        formatAddress.append ( "<address2><![CDATA[" + add.getAddress3 () );
        if( add.getAddress3() != null && !add.getAddress3().trim().equalsIgnoreCase( "" ) && add.getAddress4() != null && !add.getAddress4().trim().equalsIgnoreCase( "" ) )
        formatAddress.append ( ", " );
        formatAddress.append ( add.getAddress4() );
        formatAddress.append ( "]]></address2>" + "\n" );

        StringBuffer cityStateZip = new StringBuffer ( "" );

        if ( !"".equals( add.getCity () ) ) cityStateZip.append ( add.getCity () );
        // add ',' only if city, state, zip are not empty
        if ( !"".equals( add.getCity () ) && ( !"".equals( add.getState() ) || !"".equals( add.getZipCode() ) ) ) cityStateZip.append ( ", " );
        if ( !"".equals( add.getState() ) ) cityStateZip.append ( add.getState () );
        // Add '-' only if there is state and Zip also
        if ( !"".equals( add.getState() ) && !"".equals( add.getZipCode() ) ) cityStateZip.append ( " - " );
        if ( !"".equals( add.getZipCode() ) ) cityStateZip.append ( add.getZipCode () );
        // add ',' if any of the above is present
        if ( ( !"".equals ( add.getCity() ) || !"".equals( add.getState() ) || !"".equals( add.getZipCode() ) ) && !"".equalsIgnoreCase( add.getCountry() ) ) cityStateZip.append ( ", " );
        cityStateZip.append ( add.getCountry () );

        formatAddress.append ( "<cityStateZip><![CDATA[" + cityStateZip + "]]></cityStateZip>" + "\n" );

        StringBuffer phFax = new StringBuffer ();
        if( !"".equals( add.getPhoneNumber() ) ) phFax.append( "T:" + add.getPhoneNumber () );
        if( !"".equals( add.getPhoneNumber() ) && !"".equals( add.getFaxNumber() ) ) phFax.append ( "," );
        if( !"".equals( add.getFaxNumber() ) ) phFax.append( "F:" + add.getFaxNumber () );
        formatAddress.append ( "<phoneFax><![CDATA[" + phFax + "]]></phoneFax>" + "\n" );

        formatAddress.append ( "<email><![CDATA[" );
        formatAddress.append ( ( ( add.getEmail() != null ) && ( add.getEmail().trim().length() > 0 ) ) ? "Email: "+ add.getEmail() : "" );
        formatAddress.append ( "]]></email> \n" );

        return formatAddress.toString() ;
    }

}